package com.power.test.model.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.power.test.model.date.DateTimeHelper;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * LocalDateTime 反序列化器
 */
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> implements ContextualDeserializer {
    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            //时间戳字符串
            String value = jsonParser.getText();
            if (StringUtils.isBlank(value))
                return null;

            value = value.trim();
            String yyMMdd = "yyyy-MM-dd";
            String yyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
            String yyMMddHHmmssSSS = "yyyy-MM-dd HH:mm:ss.SSS";
            LocalDateTime result = null;
            if (value.length() == yyMMdd.length()) {
                result = DateTimeHelper.strToLocalDateTime(value, yyMMdd);
            } else if (value.length() == yyMMddHHmmss.length()) {
                result = DateTimeHelper.strToLocalDateTime(value, yyMMddHHmmss);
            } else if (value.length() == yyMMddHHmmssSSS.length()) {
                result = DateTimeHelper.strToLocalDateTime(value, yyMMddHHmmssSSS);
            }
            if (result == null) {
                //时间戳
                Long time = new Long(value);
                Instant instant;
                if (value.length() == 10) {
                    //10位时间戳 秒级 1612627200
                    instant = Instant.ofEpochSecond(time);
                } else {
                    //13位时间戳 毫秒级 1612627200000
                    instant = Instant.ofEpochMilli(time);
                }
                //返回时间格式，采用当地格式
                result = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            }

            return result;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
        return new LocalDateTimeDeserializer();
    }
}
